package com.example.finalwork

import android.content.Intent
import android.os.Bundle
import android.os.CancellationSignal
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.finalwork.LoginActivity
import com.example.finalwork.database.AppDatabase
import com.example.finalwork.databinding.ActivityRegisterBinding
import com.example.finalwork.pojo.UserInfo
import kotlinx.coroutines.launch

class RegisterActivity : AppCompatActivity() {
    private lateinit var binding: ActivityRegisterBinding
    private lateinit var db: AppDatabase

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRegisterBinding.inflate(layoutInflater)
        setContentView(binding.root)

        db = AppDatabase.getDatabase(this)

        binding.btnRegister.setOnClickListener {
            val username = binding.etUsername.text.toString().trim()
            val password = binding.etPassword.text.toString().trim()
            val repassword = binding.etRepassword.text.toString().trim()

            if (username.isNotEmpty() && password.isNotEmpty() && repassword.isNotEmpty() && password == repassword) {
                lifecycleScope.launch {
                    val existingUser = db.userDao().getUserByUsername(username)
                    if (existingUser == null) {
                        val userInfo = UserInfo(username, password)
                        db.userDao().insertUser(userInfo) // 使用 Room 插入用户
                        Toast.makeText(this@RegisterActivity, "注册成功", Toast.LENGTH_SHORT).show()
                        val intent = Intent(this@RegisterActivity, LoginActivity::class.java)
                        startActivity(intent)
                        finish()
                    } else {
                        Toast.makeText(this@RegisterActivity, "用户名已存在", Toast.LENGTH_SHORT).show()
                    }
                }
            } else {
                Toast.makeText(this, "请确保所有字段都填写正确", Toast.LENGTH_SHORT).show()
            }
        }

        binding.tvLogin.setOnClickListener {
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
        }
    }
}
